package com.killer.catalina;

import com.killer.util.HttpProtocolUtil;
import com.killer.view.Request;
import com.killer.view.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * Host的实现类
 */
public class StandardHost implements Host{

    /**
     * 虚拟主机名称
     */
    private String name;

    /**
     * 资源对应的目录
     */
    private String appBase;

    /**
     * 一个Host可以配置多个context
     */
    private List<Context> contextList;

    public List<Context> getContextList() {
        return contextList;
    }

    public void setContextList(List<Context> contextList) {
        this.contextList = contextList;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }

    @Override
    public void start() {
        //启动下面所有的Context
        if (CollectionUtils.isNotEmpty(contextList)) {
            for (Context context : contextList) {
                context.start();
            }
        }
    }

    public StandardContext mapperContext(Request request, Response response) throws IOException {
        if (CollectionUtils.isEmpty(contextList)) {
            response.response(HttpProtocolUtil.getRep404Header());
        }
        for (Context context : contextList) {
            //    /webDemo01/index.html
            //由于MiniCat默认都必须给应用命名，因此/至少2个，实际情况是可以一个的，获取第一个/和第二个/之间的内容
            String path=request.getPath();
            String appName = path.substring(path.indexOf("/"), path.indexOf("/", 1));
            StandardContext standardContext=(StandardContext)context;
            if (StringUtils.equals(appName, standardContext.getPath())) {
                return standardContext;
            }
        }
        return null;
    }
}
